<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 18-12-29
 * Time: 下午8:06
 */

namespace app\models;


use app\components\exceptions\InvalidRequestException;
use Yii;

trait Common
{
    /**
     * 装载并验证数据
     * @param $data
     * @param $scenario
     */
    public function loadData($data=[], $scenario='')
    {
        //默认加载post的数据
        $data || $data=Yii::$app->request->post();
        //有场景才进行设置
        $scenario && $this->scenario=$scenario;

        $this->load($data);

        if(!$this->validate()){
            //取第一句错误信息抛出
            $msg=current($this->errors);
            throw new InvalidRequestException(1001,$msg[0]);
        }

        return $this;
    }
}